
module spi_rx_buf(
    // APB interface
    input                               pclk_i,
    input                               prstn_i,
    input  [31:0]                       paddr_i,
    input                               penable_i,
    input                               psel_i,
    input  [2 :0]                       pprot_i,
    input  [31:0]                       pwdata_i,
    input                               pwrite_i,
    output reg [31:0]                   prdata_o,

    // spi fsm ctrl
    input                               rxdata_state_i,
    input                               rx_1b_data_done_i,
    input                               byte_cnt_flag_i,
    input  [7 :0]                       rdata_i                             
);

reg  [7:0]                              raddr_cnt;
wire [31:0]                              rdata;
wire                                    wen;

// APB 读
always@(posedge pclk_i or negedge prstn_i)begin
    if(!prstn_i)begin
        prdata_o <= 'd0;
    end
    else if((psel_i == 1'b1) && (penable_i == 1'b0) && (pwrite_i == 1'b0))begin
        prdata_o <= rdata;
    end
end

// 控制器写数据
assign wen = (rxdata_state_i && rx_1b_data_done_i) ? 1'b1 : 1'b0;
always@(posedge pclk_i or negedge prstn_i)begin
    if(!prstn_i)begin
        raddr_cnt <= 'd0;
    end
    else if(rxdata_state_i & rx_1b_data_done_i & byte_cnt_flag_i)begin
        raddr_cnt <= 'd0;
    end
    else begin
        if(rxdata_state_i)begin
            raddr_cnt <= rx_1b_data_done_i ? (raddr_cnt + 1'b1) : raddr_cnt;
        end
        else begin
            raddr_cnt <= 'd0;
        end
    end
end

rx_buf_4_8_64 u_rx_buf_4_8_64(
    .clk_i          (   pclk_i      ),
    .rstn_i         (   prstn_i     ),

    .wen_i          (   wen         ),
    .waddr_i        (   raddr_cnt   ),
    .wdata_i        (   rdata_i     ),

    .raddr_i        (   paddr_i     ),
    .rdata_o        (   rdata       )   
);
endmodule